package com.cysion.study.widget;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.FloatRange;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cysion.study.MainActivity;
import com.cysion.study.R;
import com.cysion.study.ui.login.LoginActivity;

import java.net.URISyntaxException;
import java.util.List;

import static com.cysion.study.widget.ToastUtilKt.ShowToast;


/**
 * 界面帮助类
 *
 * @author XuYang
 */
public class UIHelper {
    /**
     * 方法描述：判断某一应用是否正在运行
     *
     * @param context     上下文
     * @param packageName 应用的包名
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }


    public static void jump(Activity context, Class clazz) {
        Intent intent = new Intent(context, clazz);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void jump(Activity context, Class clazz, Bundle bundle) {
        Intent intent = new Intent(context, clazz);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public static void jumpForResult(Activity context, Class clazz,
                                     int requestCode) {
        Intent intent = new Intent(context, clazz);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivityForResult(intent, requestCode);
    }

    public static void jumpForResult(Activity context, Class clazz,
                                     Bundle bundle, int requestCode) {
        Intent intent = new Intent(context, clazz);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtras(bundle);
        context.startActivityForResult(intent, requestCode);
    }

    public static void jumpForResult(Fragment fragment, Class clazz,
                                     Bundle bundle, int requestCode) {
        Intent intent = new Intent(fragment.getActivity(), clazz);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtras(bundle);
        fragment.startActivityForResult(intent, requestCode);
    }



    //com.autonavi.minimap
    // com.baidu.BaiduMap
    //判断是否安装地图应用
    private static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    //百度
    public static void goToBaidu(Context context, String lat, String lon, String address) throws URISyntaxException {
        if (!checkApkExist(context, "com.baidu.BaiduMap")) {
            ShowToast("未安装百度地图app，无法进行线路导航");
            return;
        }
        Uri uri = Uri.parse("baidumap://map/direction?destination=latlng:"+lat+","+ lon+"|name:"+address+"&mode=driving");
        context.startActivity(new Intent(Intent.ACTION_VIEW, uri));

//        Intent intent = Intent.getIntent("intent://map/direction?destination=latlng:" + latLng + "|name:" + address + "&mode=driving&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");
//        context.startActivity(intent);
    }



    private static String lastToast = "";
    private static long lastToastTime;

    public static void showToast(Context context, String message) {
        showToast(context, message, Gravity.BOTTOM);
    }

    public static void showToast(Context context, String message, int gravity) {
        if (message != null && !message.equalsIgnoreCase("")) {
            long time = System.currentTimeMillis();
            if (!message.equalsIgnoreCase(lastToast) || Math.abs(time - lastToastTime) > 2000) {
                View view = LayoutInflater.from(context).inflate(R.layout.view_toast, null);
                ((TextView) view.findViewById(R.id.title_tv)).setText(message);
                /*if (icon != 0) {
                    ((ImageView) view.findViewById(R.id.icon_iv)).setImageResource(icon);
                    ((ImageView) view.findViewById(R.id.icon_iv)).setVisibility(View.VISIBLE);
                }*/
                Toast toast = new Toast(context);
                toast.setView(view);
                if (gravity == Gravity.CENTER) {
                    toast.setGravity(gravity, 0, 0);
                } else {
                    toast.setGravity(gravity, 0, (int) dpToPixel(context, 60));
                }

                toast.setDuration(Toast.LENGTH_SHORT);
                toast.show();
                lastToast = message;
                lastToastTime = System.currentTimeMillis();
            }
        }
    }

    public static float dpToPixel(Context context, float dp) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displaymetrics);
        return dp * (displaymetrics.densityDpi / 160F);
    }
    /**
     * 点击返回监听事件
     */
    public static View.OnClickListener finish(final Activity activity) {
        return new View.OnClickListener() {
            public void onClick(View v) {
                activity.finish();
            }
        };
    }


    /**
     * 点击返回监听事件
     */
    public static View.OnClickListener OnClickJump(final Activity context, final Class clazz) {
        return new View.OnClickListener() {
            public void onClick(View v) {
                jump(context, clazz);
            }
        };
    }

    /**
     * 显示启动页面
     *
     * @param context
     */
    public static void showAppStart(Context context, boolean isClearTask) {
        Intent intent = new Intent(context, MainActivity.class);
        if (isClearTask) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    /**
     * 显示登录页面
     *
     * @param context
     */
    public static void showLogin(Context context, boolean isClearTask) {
        Intent intent = new Intent(context, LoginActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        if (isClearTask) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }


    /**
     * 显示主页面clear_top
     *
     * @param context
     */
    public static void showMainWithClearTop(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    /**
     * 显示忘记密码页面
     *
     * @param context
     */
    public static void showForgetPwd(Context context) {
//        Intent intent = new Intent(context, FindPwdActivity.class);
//        context.startActivity(intent);
    }

    /**
     * 显示修改密码页面
     *
     * @param context
     */
    public static void showModifyPwd(Context context) {
//        Intent intent = new Intent(context, ModifyPwdActivity.class);
//        context.startActivity(intent);
    }
    /**
     * 查看图片
     *
     * @param context
     * @param beans
     * @param startIndex
     */
    /*public static void showImages(Context context, ArrayList<ImageBean> beans, int startIndex) {
        Intent intent = new Intent(context, ImageViewerActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(ImageViewerActivity.BUNDLE_KEY_IMAGE_BEANS, beans);
        bundle.putInt(ImageViewerActivity.BUNDLE_KEY_START_INDEX, startIndex);
        intent.putExtras(bundle);
        ((Activity) context).startActivityForResult(intent, ImageViewerActivity.REQUEST_CODE_IMAGE_VIEWER);
    }*/

    /**
     * 查看图片
     *
     * @param context
     * @param beans
     * @param startIndex
     * @param isCheckMode
     */
    /*public static void showImages(Context context, ArrayList<ImageBean> beans, int startIndex, boolean isCheckMode) {
        Intent intent = new Intent(context, ImageViewerActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(ImageViewerActivity.BUNDLE_KEY_IMAGE_BEANS, beans);
        bundle.putInt(ImageViewerActivity.BUNDLE_KEY_START_INDEX, startIndex);
        bundle.putBoolean(ImageViewerActivity.BUNDLE_KEY_IS_CHECK_MODE, isCheckMode);
        intent.putExtras(bundle);
        ((Activity) context).startActivityForResult(intent, ImageViewerActivity.REQUEST_CODE_IMAGE_VIEWER);
    }*/

    /**
     * 开启app更新服务
     *
     * @param context
     * @param downUrl
     */
    /*public static void startUpdateSevice(Context context, String downUrl) {
        Intent intent = new Intent(context, UpdateService.class);
        intent.putExtra(UpdateService.BUNDLE_KEY_DOWN_URL, downUrl);
        context.startService(intent);
    }*/

    // =============================================================tools
    // methods


    /**
     * 获取状态栏的高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources()
                    .getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideInputMethod(View view) {
        try {
            InputMethodManager imm = (InputMethodManager) view.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public static void hideInputMethod(final View view, long delayMillis) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                hideInputMethod(view);
            }
        }, delayMillis);
    }

    /**
     * 显示软键盘
     */
    public static void showInputMethod(View view) {
        if (view == null) return;
        if (view instanceof EditText) view.requestFocus();
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            boolean success = imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);

        }
    }

    /**
     * 显示软键盘
     */
    public static void showInputMethod(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 多少时间后显示软键盘
     */
    public static void showInputMethod(final View view, long delayMillis) {
        if (view != null)
        // 显示输入法
        {
            view.postDelayed(new Runnable() {

                @Override
                public void run() {
                    UIHelper.showInputMethod(view);
                }
            }, delayMillis);
        }
    }


    /**
     * 调整窗口的透明度
     *
     * @param from
     * @param to
     */
    private void dimBackground(Activity act, @FloatRange(from = 0.0f, to = 1.0f) final float from, @FloatRange(from = 0.0f, to = 1.0f) final float to) {
        if (act == null || act.isFinishing()) return;
        final Window window = act.getWindow();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                WindowManager.LayoutParams params = window.getAttributes();
                params.alpha = (Float) animation.getAnimatedValue();
                window.setAttributes(params);
            }
        });

        valueAnimator.start();
    }


}
